package com.xpqh.ai.controller;

import com.xpqh.ai.dto.ChatRequest;
import com.xpqh.ai.dto.ChatResponse;
import com.xpqh.ai.service.OpenAiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ChatGPT聊天控制器
 */
@RestController
@RequestMapping("/api/chat")
@Slf4j
@Validated
public class ChatController {
    
    @Autowired
    private OpenAiService openAiService;
    
    /**
     * 发送聊天消息
     */
    @PostMapping("/send")
    public ResponseEntity<ChatResponse> sendMessage(@Valid @RequestBody ChatRequest request) {
        log.info("收到聊天请求，消息：{}，模型：{}", request.getMessage(), request.getModel());
        
        ChatResponse response = openAiService.chat(request);
        
        if (response.getSuccess()) {
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取可用模型列表
     */
    @GetMapping("/models")
    public ResponseEntity<Map<String, Object>> getAvailableModels() {
        List<String> models = openAiService.getAvailableModels();
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("models", models);
        result.put("total", models.size());
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "ok");
        result.put("service", "ChatGPT API");
        result.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 简单聊天接口（只需要消息内容）
     */
    @PostMapping("/simple")
    public ResponseEntity<Map<String, Object>> simpleChat(@RequestParam String message,
                                                         @RequestParam(required = false) String model) {
        ChatRequest request = new ChatRequest();
        request.setMessage(message);
        request.setModel(model);
        
        ChatResponse response = openAiService.chat(request);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", response.getSuccess());
        result.put("content", response.getContent());
        result.put("model", response.getModel());
        result.put("totalTokens", response.getTotalTokens());
        result.put("processingTime", response.getProcessingTime());
        
        if (!response.getSuccess()) {
            result.put("error", response.getErrorMessage());
        }
        
        return ResponseEntity.ok(result);
    }
} 